<?php

namespace FileUD;

/**
 * @class   Csv
 * @author  Jon
 * @package FileUD
 * @link    https://gitee.com/joncc/file
 */
class Csv extends File
{
    /**
     * @return array|bool
     */
    public static function uploadData()
    {
        if (!self::hasFile()) {
            return false;
        }

        $file = self::getFileTmpName();

        $f = fopen($file, 'r');
        $data = [];
        while ($record = fgetcsv($f)) {
            $data[] = $record;
        }
        fclose($f);
        return $data;
    }

    /**
     * @param array $data
     * @param array $title
     * @param string $file_name
     * @return bool
     */
    public static function download($data = [], $title = [], $file_name = '')
    {
        if (!is_array($data) || !is_array($title)) {
            return false;
        }

        if (empty($file_name)) {
            $file_name = self::getTimestamp() . self::getFileSuffix();
        } else {
            $file_name .= self::getFileSuffix();
        }

        header('Content-Type:text/csv;charset=utf-8');
        header("Content-Disposition:attachment;filename={$file_name}");
        header('Expires:0');
        header('Pragma:no-cache');

        if (empty($data)) {
            return false;
        }

        $out = fopen("php://output", "w");

        if (empty($title) && isset($data[0]) && is_array($data[0])) {
            $title = array_keys($data[0]);
        }
        fputcsv($out, $title);

        foreach ($data as $record) {
            if (!is_array($record)) {
                continue;
            }

            fputcsv($out, $record);
        }
        fclose($out);
    }

    /**
     * @return string
     */
    public static function getFileSuffix()
    {
        return '.csv';
    }
}